/*
@auther fenglei
*/
package gin_api

import (
	"gitee.com/fenglei-l/ops-util/xconv"
	"github.com/duke-git/lancet/v2/convertor"
	"github.com/gin-gonic/gin"
)

const (
	//httpContentTypeJson       = "application/json"
	httpContentTypeUrlEncoded = "application/x-www-form-urlencoded"
	//httpContentTypeText       = "text/plain;charset=utf-8"
)

func ReqParam(c *gin.Context, key string) string {
	// GET 请求处理
	if c.Request.Method == "GET" {
		return c.Query(key)
	}
	// POST form-urlencoded 处理
	if c.GetHeader("Content-Type") == httpContentTypeUrlEncoded {
		return c.PostForm(key)
	}
	// POST JSON 处理
	// 从上下文中获取已解析的JSON数据
	if reqMap, exists := c.Get("reqMap"); exists {
		if m, ok := reqMap.(map[string]interface{}); ok {
			return convertor.ToString(m[key])
		}
	}
	// 如果上下文中没有，则解析并存储
	var reqMap = make(map[string]interface{})
	if err := c.ShouldBindJSON(&reqMap); err == nil {
		// 将解析后的数据存储到上下文中
		c.Set("reqMap", reqMap)
		return convertor.ToString(reqMap[key])
	}
	return ""
}
func ReqParamArray(c *gin.Context, key string) []string {
	var reqMap = make(map[string]interface{})
	if c.GetHeader("Content-Type") == httpContentTypeUrlEncoded {
		return c.PostFormArray(key)
	}
	if err := c.ShouldBindJSON(&reqMap); err != nil {
		return nil
	}
	return xconv.ToStringSlice(reqMap[key])
	//return gconv.Strings(reqMap[key])
}
